package com.atguigu.service.impl;

import com.atguigu.entity.ProductImage;
import com.atguigu.entity.ProductSalePropertyKey;
import com.atguigu.entity.ProductSalePropertyValue;
import com.atguigu.entity.ProductSpu;
import com.atguigu.mapper.ProductSpuMapper;
import com.atguigu.service.ProductImageService;
import com.atguigu.service.ProductSalePropertyKeyService;
import com.atguigu.service.ProductSalePropertyValueService;
import com.atguigu.service.ProductSpuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author GuoJH
 * @since 2021-08-24
 */
@Service
public class ProductSpuServiceImpl extends ServiceImpl<ProductSpuMapper, ProductSpu> implements ProductSpuService {
    @Autowired
    ProductImageService productImageService;
    @Autowired
    ProductSalePropertyKeyService propertyKeyService;
    @Autowired
    ProductSalePropertyValueService propertyValueService;
    //保存商品SPU信息
    @Override
    public void saveProductSpu(ProductSpu productSpu) {
        //保存productSpu信息
        baseMapper.insert(productSpu);
        //批量保存图片信息
        List<ProductImage> productImageList = productSpu.getProductImageList();
        if (!CollectionUtils.isEmpty(productImageList)){
            for (ProductImage productImage : productImageList) {
                productImage.setProductId(productSpu.getId());//遍历输入商品spu的id
            }
            productImageService.saveBatch(productImageList);//批量保存
        }
        //批量添加key的信息
        List<ProductSalePropertyKey> salePropertyKeyList = productSpu.getSalePropertyKeyList();
        if (!CollectionUtils.isEmpty(salePropertyKeyList)){
            for (ProductSalePropertyKey productSalePropertyKey : salePropertyKeyList) {
                //给商品属性key中添加商品属性spu的id
                productSalePropertyKey.setProductId(productSpu.getId());
                //遍历得到key对应的value
                List<ProductSalePropertyValue> salePropertyValueList = productSalePropertyKey.getSalePropertyValueList();
                if (!CollectionUtils.isEmpty(salePropertyValueList)){
                    for (ProductSalePropertyValue productSalePropertyValue : salePropertyValueList) {
                        //给商品属性value中添加商品属性spu的id
                        productSalePropertyValue.setProductId(productSpu.getId());
                        //添加商品属性key对应的名字
                        productSalePropertyValue.setSalePropertyKeyName(productSalePropertyKey.getSalePropertyKeyName());
                    }
                    //再批量添加商品属性对应的value值
                    propertyValueService.saveBatch(salePropertyValueList);
                }
            }
            //保存商品属性对应的key
            propertyKeyService.saveBatch(salePropertyKeyList);
        }
    }
}
